package com.ce.pms.house.web;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.ce.pms.base.web.PmsBaseAction;
import com.ce.pms.common.model.SysInfo;
import com.ce.pms.common.model.SysrefcodeDO;
import com.ce.pms.common.util.UpLoadFile;
import com.ce.pms.exception.BusinessException;
import com.ce.pms.house.service.IBuildingService;
import com.ce.pms.house.service.IHouseService;
import com.ce.pms.house.vo.FlatVO;
import com.ce.pms.house.vo.FloorVO;
import com.ce.pms.house.vo.HouseSearchVO;
import com.ce.pms.house.vo.HouseStatusVO;
import com.ce.pms.house.vo.HouseVO;
import com.ce.pms.house.vo.ImageVO;
import com.ce.util.BlankUtil;
import com.sitechasia.webx.components.xtable.util.ExtremeUtils;
import com.sitechasia.webx.core.annotation.Out;
import com.sitechasia.webx.core.annotation.Read;
import com.sitechasia.webx.core.annotation.Scope;
import com.sitechasia.webx.core.support.Page;
/**
 * 功能描述: 房屋处理类
 * <p>版权所有：中企动力
 * <p>未经本公司许可，不得以任何方式复制或使用本程序任何部分
 *
 * @author  许海堆
 * Created on  2008-6-27
 * @author
 * update on
 */
public class HouseAction extends PmsBaseAction{

	/**
	 * Function:增加页面保存
	 * @param
	 * @return
	 * Create author:xuhaidui
	 * Create on:2008-6-27
	 * Edit author:
	 * Edit on:
	 * Why:
	 * @throws Throwable
	 */
	public String addHouse(@Read FlatVO flatVO) throws Throwable {
		UpLoadFile upLoadFile=new UpLoadFile();
		List <ImageVO> list=upLoadFile.parseFormAndUpload(this.getRequest(), flatVO);
		for(ImageVO vo:list) {
			//平面图
			if(vo.getFieldName().indexOf("Ichnograp")>-1){
				flatVO.setIchnographyVo(vo);

			}
			//管线图
			if(vo.getFieldName().indexOf("Pipeline")>-1){
				flatVO.setPipelineVo(vo);

			}
		}
		flatVO.setCreator(this.getUserId());

		this.houseService.addHouse(flatVO);

		if("true".equals(flatVO.getSaveAgain())){
			this.getRequest().setAttribute("hasSaveAgain", "true");
		  return initialHouseAdd(flatVO.getBuildingId(),flatVO.getProjectId());
		}else{
			return "onlyRefreshHouse";
		}

	}

	/**
	 * Function:初始化增加页面
	 * @param
	 * @return
	 * Create author:xuhaidui
	 * Create on:2008-6-27
	 * Edit author:
	 * Edit on:
	 * Why:
	 */
	public String initialHouseAdd(@Read(key="buildingId")@Out(key="buildingId")Long buildingId,
			@Read(key="projectId")@Out(key="projectId")Long projectId) {

		//楼栋单元列表
		this.getRequest().setAttribute("houseGrpList", buildingService.getBuildingCellList(buildingId));

		//获得楼层列表

		this.getRequest().setAttribute("houseFloorList", buildingService.getHouseStoreyList(buildingId));

		//获得户型列表
		this.getRequest().setAttribute("housePlanList", houseService.getHouseModels());

		//获得交房标准列表
		List<SysrefcodeDO> deliveryLimitationList=getSysCodoList(SysrefcodeDO.CS_FLAT_DELIVERY_STANDARD_CODE);
		this.getRequest().setAttribute("deliveryLimitationList", deliveryLimitationList);

		List directionList = getSysCodoList(SysrefcodeDO.CS_FLAT_WINDOW_FACE_CODE);
		this.getRequest().setAttribute("buildingId", buildingId);
		this.getRequest().setAttribute("directionList", directionList);


		return "houseAdd";
	}

	/**
	 * Function:初始化修改页面
	 * @param
	 * @return
	 * Create author:xuhaidui
	 * Create on:2008-6-27
	 * Edit author:
	 * Edit on:
	 * Why:
	 */
	public String initialHouseEdit(@Read(key="keyword")Long keyword,
			@Read(key="projectId")@Out(key="projectId")Long projectId) {
		FlatVO flat = (FlatVO) houseService.getFlatHouseById(keyword);
		//楼栋单元列表
		this.getRequest().setAttribute("houseGrpList", buildingService.getBuildingCellList(flat.getBuildingId()));

		if("0".equals(flat.getHasCustomer()))//1:不允许修改,0:允许修改
		{

			//获得楼层列表

			this.getRequest().setAttribute("houseFloorList", buildingService.getHouseStoreyList(flat.getBuildingId()));

			//获得户型列表
			this.getRequest().setAttribute("housePlanList", houseService.getHouseModels());

			//获得交房标准列表
			List<SysrefcodeDO> deliveryLimitationList=getSysCodoList(SysrefcodeDO.CS_FLAT_DELIVERY_STANDARD_CODE);
			this.getRequest().setAttribute("deliveryLimitationList", deliveryLimitationList);
		}
		List directionList = getSysCodoList(SysrefcodeDO.CS_FLAT_WINDOW_FACE_CODE);
		this.getRequest().setAttribute("buildingId", flat.getBuildingId());
		this.getRequest().setAttribute("directionList", directionList);
		setAttribute("canAllowModify", flat.getHasCustomer());
		setAttribute("flat", flat);

		return "houseEdit";
	}


	/**
	 * Function:修改保存页面
	 * @param
	 * @return
	 * Create author:xuhaidui
	 * Create on:2008-6-27
	 * Edit author:
	 * Edit on:
	 * Why:
	 */
	public String updateHouse(@Read FlatVO flatVO) throws Throwable{
		UpLoadFile upLoadFile=new UpLoadFile();
		List <ImageVO> list=upLoadFile.parseFormAndUpload(this.getRequest(), flatVO);
		ImageVO ichnograp=new ImageVO();
		ImageVO pipeline=new ImageVO();
		if(list.size()>0)
		{
			for(ImageVO vo:list) {
				//平面图
				if(vo.getFieldName().indexOf("Ichnograp")>-1){
					ichnograp=vo;
				}
				//管线图
				if(vo.getFieldName().indexOf("Pipeline")>-1){
					pipeline=vo;
				}
			}
		}
		upLoadFile.wrapImage("Pipeline", pipeline);
		upLoadFile.wrapImage("Ichnograp", ichnograp);
		flatVO.setIchnographyVo(ichnograp);
		flatVO.setPipelineVo(pipeline);
		flatVO.setCreator(this.getUserId());
		houseService.editHouse(flatVO);
		return "onlyRefreshHouse";
	}


	/**
	 * Function:根据房间的id删除房间
	 * @param
	 * @return
	 * Create author:xuhaidui
	 * Create on:2008-6-27
	 * Edit author:
	 * Edit on:
	 * Why:
	 */
	public String deleteHouse(@Read(key="keyword")Long keyword) {
		try {
			List<ImageVO> imageList = new ArrayList<ImageVO>();
			this.houseService.deleteHouse(keyword,imageList);
			UpLoadFile.deleteFile(imageList);

		} catch(BusinessException be){
			throw be;
		} catch (Exception e) {
			super.logger.error(e.getMessage(), e);
			throw new BusinessException("house:house_delete_failure_exception",BusinessException.FAILURE);
		}

		return "onlyRefreshHouse";
	}

	/**
	 * Function:初始化详细的主页面
	 * @param
	 * @return
	 * Create author:xuhaidui
	 * Create on:2008-7-7
	 * Edit author:
	 * Edit on:
	 * Why:
	 */
	public String initHouseDetailMain(@Read(key="keyword")Long keyword){
		this.getRequest().setAttribute("houseId", keyword);
		return "houseDetailMain";
	}

	/**
	 * Function:初始化详细的主页面
	 * @param
	 * @return
	 * Create author:xuhaidui
	 * Create on:2008-7-7
	 * Edit author:
	 * Edit on:
	 * Why:
	 */
	public String initHouseDetail(@Read(key="keyword")Long keyword,
			@Read(key="overflowHight",defaultValue="")@Out(key="overflowHight")String overflowHight){
		FlatVO vo=(FlatVO)houseService.getFlatHouseById(keyword);
		this.getRequest().setAttribute("filePath", UpLoadFile.getUploadFilePath());
		this.getRequest().setAttribute("houseVO", vo);
		return "houseDetail";
	}

	/**
	 * Function:查询图示的列表
	 * @param
	 * @return
	 * Create author:xuhaidui
	 * Create on:2008-6-27
	 * Edit author:
	 * Edit on:
	 * Why:
	 */
	public String housesIconList(@Read HouseSearchVO houseSearchVO,
			                  @Read(key = "ec_crd",defaultValue="9")int pageSize,
                              @Read(key = "ec_p", defaultValue="1")	int pageNo) {


		if(BlankUtil.isBlank(houseSearchVO.getHouseStatusCode())) {
			List<HouseStatusVO> list=houseService.queryDifferentStatusHouseStatusListBybuildingId(houseSearchVO.getBuildingId());
		   setAttribute("houseStatusList", list,Scope.SESSION);
		}

		Map<Integer, Object> map = null;

		map = this.houseService.queryHouseIconListByPage(houseSearchVO, pageNo, pageSize);

		Integer tmpMaxHouseCount = (Integer)map.get(0);

		List<FloorVO> floorVOList = (List<FloorVO>)map.get(1);

		Integer totalRows = (Integer)map.get(2);

		this.getRequest().setAttribute("HouseIcomList", floorVOList);
		this.getRequest().setAttribute("maxHouseCount", tmpMaxHouseCount);
		this.getRequest().setAttribute("totalRows", totalRows);
		this.getRequest().setAttribute("buildingId", houseSearchVO.getBuildingId());
		return "houseIconList";
	}

	/**
	 * Function:查询房屋的列表
	 * @param
	 * @return
	 * Create author:xuhaidui
	 * Create on:2008-6-27
	 * Edit author:
	 * Edit on:
	 * Why:
	 */
	public String housesList( @Read HouseSearchVO houseSearchVO,
			                  @Read(key = "ec_crd",defaultValue="15")	int pageSize,
                              @Read(key = "ec_p", defaultValue="1")	int pageNo) {

		houseSearchVO.setSortStr(ExtremeUtils.getOrderString(this.getRequest()));

        Page page  = this.houseService.queryHouseListByPage(houseSearchVO, pageNo, pageSize);
		List<FlatVO> list = page.getResult();
		Long totalRows = page.getTotalCount();
		this.getRequest().setAttribute("HouseList", list);
		this.getRequest().setAttribute("totalRows", totalRows.intValue());
		this.getRequest().setAttribute("buildingId", houseSearchVO.getBuildingId());
		if(!BlankUtil.isBlank(houseSearchVO)){
		    this.getRequest().setAttribute("houseNumber", houseSearchVO.getHouseNumber());
		}

		return "houseList";
	}

	/**
	 * Function:前台验证房间号码是否已经存在(增加房间时)
	 * @param
	 * @return
	 * Create author:xuhaidui
	 * Create on:2008-7-14
	 * Edit author:
	 * Edit on:
	 * Why:
	 */
	public void validationHouseNumber(@Read(key = "projectId")	Long projectId,
			@Read(key = "houseNumber")	String houseNumber) {

		try{
			if(houseService.checkIsOnlyHouseNoInHouseAndCoalitionHouse(projectId, houseNumber)){

				this.renderText(this.getLocaleMessage("house:house_number_exist_exception"));
			}else {

				this.renderText("true");
			}
		} catch(Exception ex) {
			this.renderText("false");
		}

	}

	/**
	 * Function:前台验证房间号码是否已经存在(修改房间时)
	 * @param
	 * @return
	 * Create author:xuhaidui
	 * Create on:2008-7-14
	 * Edit author:
	 * Edit on:
	 * Why:
	 */
	public void validationHouseNumberEdit(@Read(key = "projectId")	Long projectId,
			                          @Read(key="keyword")Long keyword,
			                          @Read(key = "houseNumber")	String houseNumber) {

		try{
			if(houseService.checkIsOnlyHouseNoInHouseAndCoalitionHouse(projectId, keyword, houseNumber)){

				this.renderText(this.getLocaleMessage("house:house_number_exist_exception"));
			}else {

				this.renderText("true");
			}
		} catch(Exception ex) {
			this.renderText("false");
		}

	}

	/**
	 * Function:更改房间的状态
	 * @param
	 * @return
	 * Create author:xuhaidui
	 * Create on:2008-6-27
	 * Edit author:
	 * Edit on:
	 * Why:
	 */
	public String updateHouseState(@Read(key="keyword")Long houseId,
			@Read(key="houseState")Long houseState) {
		HouseVO houseVo = this.houseService.modifyHouseStatus(houseId, houseState);
		return "onlyRefreshHouse";
	}

	/**
	 * 功能描述:初始化改变房间状态页面
	 * @param
	 * @return
	 *
	 * Create author:xuhaidui
	 * Create on:2008-7-21
	 * Edit author:
	 * Edit on:
	 * Why:
	 */
	public String initHouseStatePage(@Read(key="keyword")Long keyword){
		this.getRequest().setAttribute("keyword", keyword);

		if (!this.houseService.checkHouseStatusCanbeModified(keyword)) {
			throw new BusinessException("house:house_status_modify_exception",BusinessException.WARNING);
		}

		StringBuilder valueString = new StringBuilder();
		valueString.append("'").append(SysrefcodeDO.HM_HOUSE_HOUSE_STATUS_VALUE_RENTAL).append("'");
		valueString.append(SysInfo.SEPARATOR_COMMA);
		valueString.append("'").append(SysrefcodeDO.HM_HOUSE_HOUSE_STATUS_VALUE_SINCETHELIVING).append("'");
		valueString.append(SysInfo.SEPARATOR_COMMA);
		valueString.append("'").append(SysrefcodeDO.HM_HOUSE_HOUSE_STATUS_VALUE_VACANT).append("'");
        this.getRequest().setAttribute("houseStateList", houseService.getHouseStatuses(valueString.toString()));
		return "houseStateChange";
	}


	private IBuildingService buildingService;

	public void setBuildingService(IBuildingService buildingService) {
		this.buildingService = buildingService;
	}

	private IHouseService houseService;

	public void setHouseService(IHouseService houseService) {
		this.houseService = houseService;
	}



	private List<SysrefcodeDO> getSysCodoList(String code){
		if(BlankUtil.isBlank(code))
			return null;
		return sysrefcodeService.querySysrefCodesByCode(code);
	}

}
